package org.jeecg.modules.demo.DPT.job;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.DPT.entity.Ticket;
import org.jeecg.modules.demo.DPT.service.ITicketService;
import org.jeecg.modules.demo.DptAccount.entity.DptAccount;
import org.jeecg.modules.demo.DptAccount.service.IDptAccountService;
import org.jeecg.modules.demo.TicketDataString.entity.TicketDataString;
import org.jeecg.modules.demo.TicketDataString.service.ITicketDataStringService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 同步电票通发票池到本地
 * 
 * @Author Scott
 */
@Slf4j
@Component
public class SynTicketJob implements Job {

	@Autowired
	ITicketService ticketService;
	@Autowired
	ITicketDataStringService ticketDataStringService;
	@Autowired
	IDptAccountService dptAccountService;
	@SneakyThrows
	@Override
	public void execute(JobExecutionContext jobExecutionContext) {
		// 获取当前日期
		Calendar calendar = Calendar.getInstance();

		// 格式化今天日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String todayStr = sdf.format(calendar.getTime());
		String todayStr1 = "2026-1-1";

		// 获取昨天日期
		calendar.add(Calendar.DAY_OF_MONTH, -1);
		String yesterdayStr = sdf.format(calendar.getTime());
		String yesterdayStr1 = "2020-1-1";

		String parameter = jobExecutionContext.getMergedJobDataMap().getString("parameter");
		if (parameter!=null){
			yesterdayStr=parameter;
		}

		List<DptAccount> list = dptAccountService.list();
		for (DptAccount dptAccount : list) {
			String token = dptAccount.getToken();
			String spid = dptAccount.getSpid();
			String corpName = dptAccount.getCorpName();
			JSONObject rspPageCal = getSynTicket( token, 1, 1, spid, yesterdayStr, todayStr);
//		JSONArray rowsPageCal = rspPageCal.getJSONArray("rows");
			if(rspPageCal.getString("Result").equals("0")){
				log.info(corpName+"获取出错");
				log.info(rspPageCal.toJSONString());
				continue;
			}
			Integer total = Integer.valueOf(rspPageCal.getString("total"));
			BigDecimal totalcal = new BigDecimal(total);
			Integer page=1;
			log.info(corpName+"数量："+totalcal);
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			while (totalcal.divide(BigDecimal.valueOf(1000), RoundingMode.UP).compareTo(new BigDecimal(page))>=0){
				JSONObject rsp = getSynTicket( token, page, 1000, spid, yesterdayStr, todayStr);
				JSONArray rows = rsp.getJSONArray("rows");
				log.info(corpName+"发票同步第"+page+"页，数量："+rows.size());
				page++;
				for (Object row : rows) {
					Ticket ticket = saveTicket(row);
				}
			}
		}

	}

	SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	Integer chunkSize=200;
	public Ticket saveTicket(Object row) throws ParseException {
		String fphm = ((JSONObject) row).getString("FPHM");
//			同步到本地
		Long count = ticketService.query().eq("FPHM", fphm).count();
		if(count>0){
			Ticket ticket = ticketService.query().eq("FPHM", fphm).one();
			if(ticket.getDownloadurl()==null||ticket.getDownloadurl().isEmpty()){
				String SJURL_PDF = ((JSONObject) row).getString("SJURL_PDF");
				ticket.setDownloadurl(SJURL_PDF);
				ticketService.updateById(ticket);
			}
			return ticket;
		}
		Ticket ticket = new Ticket();
//			购方名称
		ticket.setKhmc(((JSONObject) row).getString("KHMC"));
//			开票人
		ticket.setKpr(((JSONObject)row).getString("KPR"));
//			销方名称
		ticket.setXfmc(((JSONObject)row).getString("XFMC"));
//			票种说明
		ticket.setPzsm(((JSONObject)row).getString("PZSM"));
//			整张发票金额
		ticket.setKpje(new BigDecimal(((JSONObject)row).getString("KPJE")));
//			购方税号
		ticket.setKhsh(((JSONObject)row).getString("KHSH"));
//			整张发票税额
		ticket.setKpse(new BigDecimal(((JSONObject)row).getString("KPSE")));
//			发票种类
		ticket.setFpzl(((JSONObject)row).getString("FPZL"));
//			销方税号
		ticket.setXfsh(((JSONObject)row).getString("XFSH"));
		String time = ((JSONObject) row).getString("TIME");
//		下载链接
		String SJURL_PDF = ((JSONObject) row).getString("SJURL_PDF");
		ticket.setDownloadurl(SJURL_PDF);
		Date parse = sdf1.parse(time);
		ticket.setTickettime(parse);
//			备注
		ticket.setRemark(((JSONObject)row).getString("BZ"));
		ticket.setProjecttype("未关联");
		String mxlist = ((JSONObject) row).getString("MXLIST");
		JSONArray projects = JSONArray.parseArray(mxlist);
		StringBuilder projectList = new StringBuilder();
		Map<String, String> map = new HashMap<>();
		BigDecimal bhsjeTotal = BigDecimal.ZERO;
//				项目内容
		for (Object project : projects) {
//				不含税金额
			String bhsje = ((JSONObject) project).getString("BHSJE");
			bhsjeTotal=bhsjeTotal.add(new BigDecimal(bhsje==null||bhsje.isEmpty()?"0":bhsje));
			String cpmc = ((JSONObject) project).getString("CPMC");
			if(map.get(cpmc)==null){
				map.put(cpmc,cpmc);
			}else continue;
			projectList.append(cpmc);
			projectList.append(",");
		}
		ticket.setBhsje(bhsjeTotal);
		String substring = projectList.substring(0, projectList.length() - 2);
		substring=substring.length()>500?substring.substring(0,499):substring;
		ticket.setProjectcontent(substring);
		ticket.setStatus("0");
//			发票号码
		ticket.setFphm(fphm);
		ticketService.save(ticket);
		String dataString = ((JSONObject) row).toJSONString();
		List<TicketDataString> result = new ArrayList<>();

//					同步数据裁剪
		for (int i = 0; i < dataString.length(); i += chunkSize) {
			int end = Math.min(dataString.length(), i + chunkSize);
			String chunk = dataString.substring(i, end);

			TicketDataString ticketDataString = new TicketDataString();
			ticketDataString.setMainid(ticket.getId());
			ticketDataString.setDatastring(chunk);
			ticketDataString.setSortno(i/chunkSize + 1);  // 从1开始排序
			result.add(ticketDataString);
		}
		ticketDataStringService.saveBatch(result);
//					log.info("发票号码同步："+fphm);
		return ticket;
	}

	public JSONObject getSynTicket(String token, Integer pageIndex, Integer pageSize, String spid, String begintime, String endtime){

//		获取进项发票池
		// 1. 创建 HttpClient
		HttpClient client = HttpClient.newHttpClient();
//		String params = "token=cddf62af6a834658bef9c32d497df883y3mz7qdhry" +
		String params = "token=" +token+
				"&begintime=" +begintime+
				"&endtime=" +endtime+
				"&pageindex=" +pageIndex+
				"&pagesize=" + pageSize+
//				"&spid=ee79fbeca7f9f68ae5996c3ae5b016bd";
				"&spid="+spid;
		// 3. 构建 HttpRequest
		HttpRequest request = HttpRequest.newBuilder()
				.uri(URI.create("https://fp.xinpukeji.cn/wechatapi/NEWKP/JXFPAPI/JXMX"))
				.header("Content-Type", "application/x-www-form-urlencoded") // 设置请求头
				.POST(HttpRequest.BodyPublishers.ofString(params))
				.build();

		// 4. 发送请求并获取响应
		HttpResponse<String> response = null;
		try {
			response = client.send(
					request,
					HttpResponse.BodyHandlers.ofString()
			);
			JSONObject rsp = JSONObject.parseObject(response.body());
			return rsp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
